package com.example.onlinemonitoring.model.DataFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.onlinemonitoring.model.Appdevice;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.ibatis.jdbc.Null;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import java.util.zip.CRC32;
import lombok.Data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

@Data
public class DataFileHeader {

    private int fileLength = 4260; // 文件长度，含CRC校验。 [0:3] 必备
    private int version = 1; // 规范版本号 uint8 4字节
    // 所使用的数据格式规范版本号。由4个字节组成，形如X.X.X.X。如：版本号为1.0.0.0，数组元素[0]到[3]分别存储0x01、0x00、0x00、0x00。每个字节应无符号整数，即0至255。//
    // [4:7] 必备
    private long fileGenerationTime = 13211241234L; // 文件生成时间 int64 8字节
    // 生成文件的时间，格式为YYYYMMDDhhmmssfff（年月日时分秒毫秒），例如20100818151010001。// [8:15] 必备
    private byte siteName[] = new byte[118]; // 站点名称 char 118字节使用UNICODE编码。以0x0000结尾，例如：1000 kV泉城变电站。[16:133]可选
    {
        for (int i = 0; i < siteName.length; i++) {
            siteName[i] = (byte) 0x00;
        }
    }
    private byte siteCode[] = new byte[42]; // 站点编码 char 42字节使用ASCII编码。以\0 结尾，例如：A12300000000000000。[134:175]可选
    // 使用直接赋值方式初始化为 0xFF 字节
    {
        for (int i = 0; i < siteCode.length; i++) {
            siteCode[i] = (byte) 0x00;
        }
    }
    private byte weather = (byte) 0xFF; // 天气 uint8 1字节 表示天气。未记录：0xFF晴：0x01；阴：0x02；雨：0x03；雪：0x04
    // 雾：0x05；雷雨：0x06；多云：0x07// [176:176] 可选
    private byte temperature[] = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; // 温度 float 4字节 环境温度，单位摄氏度。
                                                                                         // [177:180] 可选
    private byte humidity = (byte) 0xFF; // 湿度 int8 1字节 环境湿度，单位%。 [181:181] 可选
    private byte manufacturer[] = new byte[32]; // 装置厂家 char 32字节 使用UNICODE编码。以0x0000结尾。[182:213]必备
    private byte model[] = new byte[32]; // 装置型号 char 32字节 使用UNICODE编码。以0x0000结尾。 [214:245] 必备

    private byte softwareVersion[] = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 }; // 装置软件版本号 uint8
    // 4字节//所使用的数据格式规范版本号。由4个字节组成，形如X.X.X.X。如：版本号为1.0.0.0，数组元素[0]到[3]分别存储0x01、0x00、0x00、0x00。每个字节应无符号整数，即0至255。//
    // [246:249] 可选
    private byte serialNumber[] = new byte[32]; // 装置序列号 char 32字节使用ASCII编码。以\0 结尾，例如：S12300000000000000。[250:281]必备
    private byte systemFrequency = 50; // 系统频率 float 4字节 单位Hz。例如50Hz。 [282:285] 必备
    private short spectrumCount = 1; // 图谱数量N int16 2字节
    // 文件中包含的图谱数量。对于红外以图像形式存储的仪器，图像采集模式下图谱数量为1，视频采集模式下为存储的图谱数量；其他类型，应根据实际情况填写。
    // [286:287] 必备
    private byte longitude[] = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
            (byte) 0xFF, (byte) 0xFF }; // 经度 double 8字节 0xFFFFFFFF代表不支持该参数 [288:295] 可选
    private byte latitude[] = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
            (byte) 0xFF,
            (byte) 0xFF }; // 纬度 double 8字节 0xFFFFFFFF代表不支持该参数 [296:303] 可选
    private byte altitude[] = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }; // 海拔 int32 4字节
                                                                                      // 单位：米（m），0xFFFFFFFF代表不支持该参数
                                                                                      // [304:307] 可选
    private byte[] reserved = new byte[204]; // 预留 自定义 204字节 预留为厂家自定义可选字段。 [308:511] 可选

    // @Data
    // Inner class: PRPDGraph
    // public class PRPDGraph {
    private byte spectrumType1 = (byte) 0x21; // 图谱类型编码 uint8 1字节 标识该文件的图谱类型。应符合表C.1。 [512:512]必备
    private int spectrumDataLength1 = 3712; // 图谱数据长度L int32 4字节 图谱总长度，从图谱类型编码到图谱数据结束的长度。[513:516]必备
    private long spectrumGenerationTime1 = 1321124123412L; // 图谱生成时间 int64
    // 8字节生成图谱的时间，格式为YYYYMMDDhhmmssfff（年月日时分秒毫秒），例如20100818151010001。// [517:524]
    // 必备
    private byte spectrumProperty1 = (byte) 0x01; // 图谱性质 uint8 1字节 检测图谱：0x01；背景噪声：0x02[525:525]必备
    private byte deviceName1[] = new byte[118]; // 被测设备名称 char 118字节使用UNICODE编码。不够长度请以0x0000补充，例如：1000 kV泉城变电站#1
                                                // 主体变。[526:643]//
    // {
    // for (int i = 0; i < deviceName1.length; i++) {
    // deviceName1[i]=0x00;
    // }
    // }

    // 可选
    private byte deviceCode1[] = new byte[42]; // 被测设备编码 char 42字节使用ASCII编码。不够长度的务必以\0
    // {
    // for (int i = 0; i < deviceCode1.length; i++) {
    // deviceCode1[i]=0x00;
    // }
    // }
    // 结尾，例如：B12300000000000000。[644:685]可选
    private byte measurementPointName1[] = new byte[128]; // 测点名称 char
                                                          // 128字节表示被监测设备的监测部位或位置，使用UNICODE编码。不够长度请以0x0000补充。[686:813]可选
    private byte measurementPointCode1[] = new byte[32]; // 测点编码 char 32字节使用ASCII编码。不够长度的务必以\0
                                                         // 结尾，例如：C12300000000000000。[814:845]可选
    private short channelFlag1 = (short) 0xFF; // 检测通道标志 int16 2字节 装置的检测通道标识，例如：1。 [846:847] 可选
    private byte dataType1; // 存储数据类型t uint8 1字节 表示图谱数据的存储数据类型。应符合表C.2。 [848:848]必备
    private byte amplitudeUnit1; // 幅值单位 uint8 1字节 表示幅值的单位。应符合表C.3。 [849:849] 必备
    private float amplitudeLowerLimit1; // 幅值下限 float 4字节 装置所能检测到的信号幅值的下限。[850:853]必备
    private float amplitudeUpperLimit1; // 幅值上限 float 4字节 装置所能检测到的信号幅值的上限。[854:857]必备
    private byte bandwidth1; // 带宽（文件其他地方也替换） uint8 1字节 表示滤波类型 未记录:0xFF全通:0x01；低通:0x02；高通:0x03；可扩充:0x04//
                             // [858:858] 可选
    private float lowerFrequency1 = 0; // 下限频率 float 4字节 表示滤波的下限频率，单位Hz。 [859:862] 可选
    private float upperFrequency1 = 0; // 上限频率 float 4字节 表示滤波的上限频率，单位Hz。 [863:866] 可选
    private int phaseWindowCount1; // 相位窗数m int32 4字节工频周期被等分成m个相位窗，每个相位窗跨360/m度，m至少60。[867:870]必备
    private int amplitudeQuantization1; // 量化幅值n int32 4字节
                                        // 幅值范围的等分区间数。如果该文件是PRPS图谱，则该4个字节清零，赋值为：0x00000000。[871:874]必备
    private int powerFrequencyCycleCount1; // 工频周期数p int32
                                           // 4字节图谱工频周期的个数。如果该文件是PRPD图谱，则该4个字节清零，赋值为：0x00000000。[875:878]//
                                           // 必备
    private byte[] dischargeTypeProbability1 = new byte[8]; // 放电类型概率 uint8 8字节表示装置诊断结果的放电类型概率。[879:886]必备
    private float dischargePhase1; // 放电相位 float 4字节局放峰值或局放能量最大所在相位，单位：度，应与附录A.1.1中测量信息的数据一致[887:890]必备
    private int dischargecount1;// 次/s，应与附录A.1.1中测量信息的数据一致
    private float dischargeSignalPeak1; // 放电信号峰值 float 4字节放电信号最大值，应与附录A.1.1中测量信息的数据一致[891:894]必备
    private float dischargeSignalAverage1; // 放电信号平均值 float 4字节放电信号均方根值，应与附录A.1.1中测量信息的数据一致[895:898]必备
    private byte[] reserved21 = new byte[121]; // 预留 自定义 121字节 预留为厂家自定义可选字段。 [899:1019] 可选
    private byte[] spectrumData1 = new byte[3200]; // 局部放电图谱数据 d[m][n] 或 d[p][m] k*m*n字节或k*p*m
    // 字节//根据存储数据类型t获取数据的存储方式。实例1：t是0x02，d表示uint8数组，k=1；实例2：t是0x04，d表示int32数组，k=4；实例3：t是0x06，d表示float数组，k=4。如果该文件是PRPD图谱，则为d[m][n]，m为相位窗数，n为量化幅值，数组元素[x][y]的值表示在对应第x相位窗和第y幅值处发生的脉冲信号的次数。如果该文件是PRPS图谱，则为d[p][m]，p为工频周期数，m为相位窗数，数组元素[x][y]的值表示在对应第x个周期的第y相位窗处发生的脉冲信号的幅值。//
    // [1020:...] 必备
    // }

    // @Data
    // Inner class: PRPSGraph
    // public class PRPSGraph {
    private byte spectrumType = (byte) 0x22; // 图谱类型编码 uint8 1字节 标识该文件的图谱类型。应符合表C.1。 [512:512]必备
    private int spectrumDataLength = 3712; // 图谱数据长度L int32 4字节 图谱总长度，从图谱类型编码到图谱数据结束的长度。[513:516]必备
    private long spectrumGenerationTime = 1321124123412L; // 图谱生成时间 int64
    // 8字节生成图谱的时间，格式为YYYYMMDDhhmmssfff（年月日时分秒毫秒），例如20100818151010001。// [517:524]
    // 必备
    private byte spectrumProperty = (byte) 0x01; // 图谱性质 uint8 1字节 检测图谱：0x01；背景噪声：0x02[525:525]必备
    private byte deviceName[] = new byte[118]; // 被测设备名称 char 118字节使用UNICODE编码。不够长度请以0x0000补充，例如：1000 kV泉城变电站#1
                                               // 主体变。[526:643]//
    // 可选
    private byte deviceCode[] = new byte[42]; // 被测设备编码 char 42字节使用ASCII编码。不够长度的务必以\0
                                              // 结尾，例如：B12300000000000000。[644:685]可选
    private byte measurementPointName[] = new byte[128]; // 测点名称 char
                                                         // 128字节表示被监测设备的监测部位或位置，使用UNICODE编码。不够长度请以0x0000补充。[686:813]可选
    private byte measurementPointCode[] = new byte[32]; // 测点编码 char 32字节使用ASCII编码。不够长度的务必以\0
                                                        // 结尾，例如：C12300000000000000。[814:845]可选
    private short channelFlag = (short) 0xFF; // 检测通道标志 int16 2字节 装置的检测通道标识，例如：1。 [846:847] 可选
    private byte dataType; // 存储数据类型t uint8 1字节 表示图谱数据的存储数据类型。应符合表C.2。 [848:848]必备
    private byte amplitudeUnit; // 幅值单位 uint8 1字节 表示幅值的单位。应符合表C.3。 [849:849] 必备
    private float amplitudeLowerLimit; // 幅值下限 float 4字节 装置所能检测到的信号幅值的下限。[850:853]必备
    private float amplitudeUpperLimit; // 幅值上限 float 4字节 装置所能检测到的信号幅值的上限。[854:857]必备
    private byte bandwidth; // 带宽（文件其他地方也替换） uint8 1字节 表示滤波类型 未记录:0xFF全通:0x01；低通:0x02；高通:0x03；可扩充:0x04//
                            // [858:858] 可选
    private float lowerFrequency; // 下限频率 float 4字节 表示滤波的下限频率，单位Hz。 [859:862] 可选
    private float upperFrequency; // 上限频率 float 4字节 表示滤波的上限频率，单位Hz。 [863:866] 可选
    private int phaseWindowCount; // 相位窗数m int32 4字节工频周期被等分成m个相位窗，每个相位窗跨360/m度，m至少60。[867:870]必备
    private int amplitudeQuantization; // 量化幅值n int32 4字节
                                       // 幅值范围的等分区间数。如果该文件是PRPS图谱，则该4个字节清零，赋值为：0x00000000。[871:874]必备
    private int powerFrequencyCycleCount; // 工频周期数p int32
                                          // 4字节图谱工频周期的个数。如果该文件是PRPD图谱，则该4个字节清零，赋值为：0x00000000。[875:878]//
                                          // 必备
    private byte[] dischargeTypeProbability = new byte[8]; // 放电类型概率 uint8 8字节表示装置诊断结果的放电类型概率。[879:886]必备
    private float dischargePhase; // 放电相位 float 4字节局放峰值或局放能量最大所在相位，单位：度，应与附录A.1.1中测量信息的数据一致[887:890]必备
    private int dischargecount;// 次/s，应与附录A.1.1中测量信息的数据一致
    private float dischargeSignalPeak; // 放电信号峰值 float 4字节放电信号最大值，应与附录A.1.1中测量信息的数据一致[891:894]必备
    private float dischargeSignalAverage; // 放电信号平均值 float 4字节放电信号均方根值，应与附录A.1.1中测量信息的数据一致[895:898]必备
    private byte[] reserved2 = new byte[121]; // 预留 自定义 121字节 预留为厂家自定义可选字段。 [899:1019] 可选
    private byte[] spectrumData = new byte[3200]; // 局部放电图谱数据 d[m][n] 或 d[p][m] k*m*n字节或k*p*m
    // 字节//根据存储数据类型t获取数据的存储方式。实例1：t是0x02，d表示uint8数组，k=1；实例2：t是0x04，d表示int32数组，k=4；实例3：t是0x06，d表示float数组，k=4。如果该文件是PRPD图谱，则为d[m][n]，m为相位窗数，n为量化幅值，数组元素[x][y]的值表示在对应第x相位窗和第y幅值处发生的脉冲信号的次数。如果该文件是PRPS图谱，则为d[p][m]，p为工频周期数，m为相位窗数，数组元素[x][y]的值表示在对应第x个周期的第y相位窗处发生的脉冲信号的幅值。//
    // [1020:...] 必备
    // }
    private byte[] reserved3 = new byte[32];
    private int crc32 = 0;
    // Instantiate PRPDGraph object
    // @Autowired
    // public PRPDGraph prpdGraph = new PRPDGraph();
    // Instantiate PRPSGraph object
    // @Autowired
    // public PRPSGraph prpsGraph = new PRPSGraph();

    private float DischargeAmount;
    private String DT;
    private int Dischargecount;
    private float DischargePhase;
    private String Acqtime;
    private Appdevice ad;
    private int deviceaddr;

    public void generateprpdData(DataFileHeader header, String filename) {

        ByteBuffer buffer = ByteBuffer.allocate(10200);
        buffer.putInt(header.getFileLength());
        buffer.putInt(header.getVersion());
        buffer.putLong(header.getFileGenerationTime());
        buffer.put(header.getSiteName());
        buffer.put(header.getSiteCode());
        buffer.put(header.getWeather());
        buffer.put(header.getTemperature());
        buffer.put(header.getHumidity());
        buffer.put(header.getManufacturer());
        buffer.put(header.getModel());
        buffer.put(header.getSoftwareVersion());
        buffer.put(header.getSerialNumber());
        buffer.putFloat(header.getSystemFrequency());
        buffer.putShort(header.getSpectrumCount());
        buffer.put(header.getLongitude());
        buffer.put(header.getLatitude());
        buffer.put(header.getAltitude());
        buffer.put(header.getReserved());
        buffer.put(header.getSpectrumType1());
        buffer.putInt(header.getSpectrumDataLength1());
        buffer.putLong(header.getSpectrumGenerationTime1());
        buffer.put(header.getSpectrumProperty1());
        buffer.put(header.getDeviceName1());
        buffer.put(header.getDeviceCode1());
        buffer.put(header.getMeasurementPointName1());
        buffer.put(header.getMeasurementPointCode1());
        buffer.putShort(header.getChannelFlag1());
        buffer.put(header.getDataType1());
        buffer.put(header.getAmplitudeUnit1());
        buffer.putFloat(header.getAmplitudeLowerLimit1());
        buffer.putFloat(header.getAmplitudeUpperLimit1());
        buffer.put(header.getBandwidth1());
        buffer.putFloat(header.getLowerFrequency1());
        buffer.putFloat(header.getUpperFrequency1());
        buffer.putInt(header.getPhaseWindowCount1());
        buffer.putInt(header.getAmplitudeQuantization1());
        buffer.putInt(header.getPowerFrequencyCycleCount1());
        buffer.put(header.getDischargeTypeProbability1());
        buffer.putFloat(header.getDischargePhase1());
        buffer.putInt(header.getDischargecount1());
        buffer.putFloat(header.getDischargeSignalPeak1());
        buffer.putFloat(header.getDischargeSignalAverage1());
        buffer.put(header.getReserved21());
        buffer.put(header.getSpectrumData1());
        buffer.put(header.getReserved3());
        CRC32 crc32 = new CRC32();
        byte[] bytes = buffer.array();
        crc32.update(bytes);
        long crcVaule = crc32.getValue();
        header.setCrc32((int) crcVaule);
        buffer.putInt(header.getCrc32());

        buffer.flip(); // 切换到读模式

        // 使用try-with-resources自动关闭资源
        try (FileOutputStream fos = new FileOutputStream(filename);
                FileChannel channel = fos.getChannel()) {

            // 将ByteBuffer的内容写入FileChannel，即写入文件
            channel.write(buffer);
            channel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void generateprpsData(DataFileHeader header, String filename) {

        ByteBuffer buffer = ByteBuffer.allocate(10200);

        buffer.putInt(header.getFileLength());
        buffer.putInt(header.getVersion());
        buffer.putLong(header.getFileGenerationTime());
        buffer.put(header.getSiteName());
        buffer.put(header.getSiteCode());
        buffer.put(header.getWeather());
        buffer.put(header.getTemperature());
        buffer.put(header.getHumidity());
        buffer.put(header.getManufacturer());
        buffer.put(header.getModel());
        buffer.put(header.getSoftwareVersion());
        buffer.put(header.getSerialNumber());
        buffer.putFloat(header.getSystemFrequency());
        buffer.putShort(header.getSpectrumCount());
        buffer.put(header.getLongitude());
        buffer.put(header.getLatitude());
        buffer.put(header.getAltitude());
        buffer.put(header.getReserved());
        // if(filename.contains("_21_"))
        // {
        // buffer.put(prpdGraph.getSpectrumType());
        // buffer.putInt(prpdGraph.getSpectrumDataLength());
        // buffer.putLong(prpdGraph.getSpectrumGenerationTime());
        // buffer.put(prpdGraph.getSpectrumProperty());
        // buffer.put(prpdGraph.getDeviceName());
        // buffer.put(prpdGraph.getDeviceCode());
        // buffer.put(prpdGraph.getMeasurementPointName());
        // buffer.put(prpdGraph.getMeasurementPointCode());
        // buffer.putShort(prpdGraph.getChannelFlag());
        // buffer.put(prpdGraph.getDataType());
        // buffer.put(prpdGraph.getAmplitudeUnit());
        // buffer.putFloat(prpdGraph.getAmplitudeLowerLimit());
        // buffer.putFloat(prpdGraph.getAmplitudeUpperLimit());
        // buffer.put(prpdGraph.getBandwidth());
        // buffer.putFloat(prpdGraph.getLowerFrequency());
        // buffer.putFloat(prpdGraph.getUpperFrequency());
        // buffer.putInt(prpdGraph.getPhaseWindowCount());
        // buffer.putInt(prpdGraph.getAmplitudeQuantization());
        // buffer.putInt(prpdGraph.getPowerFrequencyCycleCount());
        // buffer.put(prpdGraph.getDischargeTypeProbability());
        // buffer.putFloat(prpdGraph.getDischargePhase());
        // buffer.putFloat(prpdGraph.getDischargecount());
        // buffer.putFloat(prpdGraph.getDischargeSignalPeak());
        // buffer.putFloat(prpdGraph.getDischargeSignalAverage());
        // buffer.put(prpdGraph.getReserved2());
        // buffer.put(prpdGraph.getSpectrumData());

        // }
        // else if(filename.contains("_22_"))
        {
            buffer.put(header.getSpectrumType());
            buffer.putInt(header.getSpectrumDataLength());
            buffer.putLong(header.getSpectrumGenerationTime());
            buffer.put(header.getSpectrumProperty());
            buffer.put(header.getDeviceName());
            buffer.put(header.getDeviceCode());
            buffer.put(header.getMeasurementPointName());
            buffer.put(header.getMeasurementPointCode());
            buffer.putShort(header.getChannelFlag());
            buffer.put(header.getDataType());
            buffer.put(header.getAmplitudeUnit());
            buffer.putFloat(header.getAmplitudeLowerLimit());
            buffer.putFloat(header.getAmplitudeUpperLimit());
            buffer.put(header.getBandwidth());
            buffer.putFloat(header.getLowerFrequency());
            buffer.putFloat(header.getUpperFrequency());
            buffer.putInt(header.getPhaseWindowCount());
            buffer.putInt(header.getAmplitudeQuantization());
            buffer.putInt(header.getPowerFrequencyCycleCount());
            buffer.put(header.getDischargeTypeProbability());
            buffer.putFloat(header.getDischargePhase());
            buffer.putInt(header.getDischargecount());
            buffer.putFloat(header.getDischargeSignalPeak());
            buffer.putFloat(header.getDischargeSignalAverage());
            buffer.put(header.getReserved2());
            buffer.put(header.getSpectrumData());

        }
        buffer.put(header.getReserved3());
        CRC32 crc32 = new CRC32();
        byte[] bytes = buffer.array();
        crc32.update(bytes);
        long crcVaule = crc32.getValue();
        header.setCrc32((int) crcVaule);
        buffer.putInt(header.getCrc32());

        buffer.flip(); // 切换到读模式

        // 使用try-with-resources自动关闭资源
        try (FileOutputStream fos = new FileOutputStream(filename);
                FileChannel channel = fos.getChannel()) {

            // 将ByteBuffer的内容写入FileChannel，即写入文件
            channel.write(buffer);
            channel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void Deletefile(String MqttfileAddr,String filename) {
        File file = new File(filename);
        // File [] list = file.listFiles();
        if (file.exists()) {
            Deletefile(MqttfileAddr,file);
        }
   
    }
    public void Deletefile(String MqttfileAddr,File file) {
        String fileAddr="";
        fileAddr = file.getName();
        if (file.isFile()) {
            if(fileAddr.contains(MqttfileAddr))
            file.delete();
        } else {
            for (File f : file.listFiles()) {
   
                Deletefile(MqttfileAddr,f);
            }
        }
    }

    public void DeleteAll(String filename) {
        File file = new File(filename);
        // File [] list = file.listFiles();
        if (file.exists()) {
            DeleteAll(file);
        }
        file.mkdir();
    }

    public void DeleteAll(File file) {

        if (file.isFile() || file.list().length == 0) {
            file.delete();
        } else {
            for (File f : file.listFiles()) {
                DeleteAll(f);
            }
        }
    }

    public String zerorFormat(String str, int len) {
        byte[] bdeviceName = new byte[1024];
        bdeviceName = str.getBytes();
        int l = bdeviceName.length;

        StringBuffer sb = new StringBuffer();
        sb.append(str);
        for (int i = 0; i < len - l; i++) {
            sb.append("\0");
        }
        return sb.toString();
    }

    public DataFileHeader setDataFile(Appdevice ad, int deviceaddr, MqttMessage message) {
        this.ad = ad;
        this.deviceaddr = deviceaddr;
        String currentPath = System.getProperty("user.dir");
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmssSSS");
        Date currenttime = new Date();
        String formattime = sdf.format(currenttime);

        setFileGenerationTime(Long.parseLong(formattime));
        byte[] bManufacturer = new byte[32];
        String Manufacturer = String.format("%s", "浙江日新电气");
        String Manufacturers = zerorFormat(Manufacturer, 32);
        bManufacturer = Manufacturers.getBytes();
        setManufacturer(bManufacturer);
        byte[] bModel = new byte[32];
        String Model = String.format("%s", "SUN-IGuard-501");
        String Models = zerorFormat(Model, 32);
        bModel = Models.getBytes();
        setModel(bModel);
        int iSerialNumber = (deviceaddr-1) / 9 + 1;
        byte[] bSerialNumber = new byte[32];
        String SerialNumber = String.format("%s%02d", "S100000000000000", iSerialNumber);
        String SerialNumbers = zerorFormat(SerialNumber, 32);
        bSerialNumber = SerialNumbers.getBytes();
        setSerialNumber(bSerialNumber);
        Random ran = new Random();
        System.out.println("message content:"+new String(message.getPayload()));
        String msg = new String(message.getPayload());
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String id = jsonObject.getString("id");
        String version = jsonObject.getString("version");
        JSONObject params = jsonObject.getJSONObject("params");
        JSONObject UHF = params.getJSONObject("UHF");
        Acqtime = UHF.getString("Acqtime");
        int phaseWindowCount = UHF.getIntValue("PhaseWindows");
        int amplitudeQuantization = UHF.getIntValue("QuantizedAmplitude");
        int powerFrequencyCycleCount = UHF.getIntValue("PowerFrequencyCycles");
        byte Unit = UHF.getByteValue("Unit");
        float MaxLimit = UHF.getFloatValue("MaxLimit");
        float MinLimit = UHF.getFloatValue("MinLimit");
        byte BandWidth = UHF.getByteValue("BandWidth");
        int AlarmLevel = UHF.getIntValue("AlarmLevel");
        int PDType = UHF.getIntValue("PDType");
        float Peak = UHF.getFloatValue("Peak");
        float Average = UHF.getFloatValue("Average");
        int DenoisingN = UHF.getIntValue("DenoisingN");
        System.out.println("DenoisingN:" + DenoisingN);
        //DischargeAmount = Peak + ran.nextInt(3);
        //Dischargecount = DenoisingN + ran.nextInt(10);
        int F50 = UHF.getIntValue("F50");
        int F100 = UHF.getIntValue("F100");
        JSONArray dischargeTypeProbability = UHF.getJSONArray("PDTypeProbability");
        JSONArray PRPD = UHF.getJSONArray("PRPD");
        JSONArray PRPS = UHF.getJSONArray("PRPS");
        int iDT = 0, ipdt = 0;
        byte[] PDTypeData = new byte[8];
        for (int i = 0; i < dischargeTypeProbability.size(); i++) {
            PDTypeData[i] = dischargeTypeProbability.getByteValue(i);
            if (iDT < PDTypeData[i]) {
                iDT = PDTypeData[i];
                ipdt++;
            }
        }
        String DischargeType[] = { "正常","尖端放电", "悬浮放电", "沿面放电", "内部放电", "颗粒放电" , "外部干扰" , "未知局放类型" };
        DT = DischargeType[ipdt];
        byte[] PRPSData = new byte[3200];
        byte[] PRPDData = new byte[3200];
        float iDischargePhase = 0;
        DischargePhase = 0;
        int MaxDischargeData = 0;
        String GisPointName = "";
        float MinDischargeData = Average ;
        int izbound = (int)(Peak - Average);
        if(izbound>10)
        izbound=10+ ran.nextInt(3);
        if(izbound<3)
        izbound=3+ ran.nextInt(3);
        //MinDischargeData = MinDischargeData - ran.nextInt(5);
        DischargeAmount = Peak + izbound ;
        if(DischargeAmount>MaxLimit)
        {
            DischargeAmount = MaxLimit;    
            izbound = (int)(MaxLimit - Peak);
        }
        Dischargecount = 0;
        int ibound = DenoisingN/10 + 1;
        if(DenoisingN==0)
        Dischargecount=0;
        else
        {
            
            Dischargecount = DenoisingN + ran.nextInt(ibound);
        }
        int iPRPSData = 0;
        int iPRPDData = 0;
        for (int i = 0; i < PRPS.size(); i++) {
            //PRPSData[i] = PRPS.getByteValue(i);
            iPRPSData = PRPS.getIntValue(i);
            if(iPRPSData<=-128)
                iPRPSData=-118;
            if(iPRPSData>=128)
                iPRPSData=118;
            ByteBuffer buffer = ByteBuffer.allocate(4);
            buffer.putInt(iPRPSData);
            PRPSData[i] =buffer.get(3);
            if (MinDischargeData > iPRPSData) {
                MinDischargeData = iPRPSData;
            }
        }
         for (int i = 0; i < PRPS.size(); i++) {
             //PRPSData[i] = PRPS.getByteValue(i);
             iPRPSData = PRPS.getIntValue(i);
             if (MaxDischargeData < iPRPSData) {
                 MaxDischargeData = iPRPSData;
                 iDischargePhase++;
             }
            if (iPRPSData == MaxLimit||iPRPSData <= -74) {      
                //ByteBuffer buffer = ByteBuffer.allocate(4);
                //buffer.putInt(iPRPSData); 
                //PRPSData[i] =buffer.get(3);
                //DischargeAmount = Peak;
            }
            else 
             {
                if ((deviceaddr % 9) == 0) {
                    iPRPSData = (int)(MinDischargeData + ran.nextInt(izbound));
                    ByteBuffer buffer = ByteBuffer.allocate(4);
                    buffer.putInt(iPRPSData);
                   // buffer.putInt(3, iPRPSData);
                    PRPSData[i] =buffer.get(3);

                    DischargeAmount = Peak = MinDischargeData + izbound ;
                    Average = MinDischargeData + ran.nextInt(izbound);
                    Dischargecount = 0;
                    for (int j = 0; j < dischargeTypeProbability.size(); j++) {
                        PDTypeData[j] = 0;
                    }
                    DT = DischargeType[4];
                } 
                else
                {
                    iPRPSData =  iPRPSData + ran.nextInt(izbound);
                    ByteBuffer buffer = ByteBuffer.allocate(4);
                    buffer.putInt(iPRPSData); 
                    PRPSData[i] =buffer.get(3);

                }
            }
         }
         DischargePhase = (iDischargePhase % powerFrequencyCycleCount) / 64 * 360;
         if(Dischargecount==0)
         DischargePhase=0;
         else if(DischargePhase==0){
            DischargePhase = ran.nextInt(360);
         }

        for (int i = 0; i < PRPD.size(); i++) {
            //PRPDData[i] = PRPD.getByteValue(i);
            iPRPDData = PRPD.getIntValue(i);
            if (iPRPDData != 0) {
                iPRPDData = iPRPDData + ran.nextInt(3);
                ByteBuffer buffer = ByteBuffer.allocate(4);
                buffer.putInt(iPRPDData);
                PRPDData[i] =buffer.get(3);
            }

        }
        if ((deviceaddr % 9) == 0)
        iPRPSData = (int)(Peak ) ;
        else
        iPRPSData = (int)(DischargeAmount) ;
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.putInt(iPRPSData); 
        PRPSData[ran.nextInt(3200)]  = buffer.get(3);
        

        byte[] bdeviceName = new byte[118];
        String deviceName = ad.getName();
        String deviceNames = zerorFormat(deviceName, 118);
        bdeviceName = deviceNames.getBytes();
        byte[] bdeviceCode = new byte[42];
        String deviceCode = String.format("%d", deviceaddr);
        String deviceCodes = zerorFormat(deviceCode, 42);
        bdeviceCode = deviceCodes.getBytes();
        byte[] bmeasurementPointName = new byte[128];
        String PointNames = GisPointName;
        String measurementPointName = zerorFormat(PointNames, 128);
        bmeasurementPointName = measurementPointName.getBytes();
        byte[] bmeasurementPointCode = new byte[32];
        String measurementPointCode = String.format("%d", 1);
        String measurementPointCodes = zerorFormat(measurementPointCode, 32);
        bmeasurementPointCode = measurementPointCodes.getBytes();
        setSpectrumGenerationTime1(Long.parseLong(formattime));
        setDeviceName1(bdeviceName);
        if((deviceaddr % 9) == 0)
            setSpectrumProperty1((byte)0x02);
        setDeviceCode1(bdeviceCode);
        setMeasurementPointName1(bmeasurementPointName);
        setMeasurementPointCode1(bmeasurementPointCode);
        setDataType1((byte) 1);
        setAmplitudeUnit1(Unit);
        setAmplitudeLowerLimit1(MinLimit);
        setAmplitudeUpperLimit1(MaxLimit);
        setBandwidth1(BandWidth);
        setPhaseWindowCount1(phaseWindowCount);
        setAmplitudeQuantization1(amplitudeQuantization);
        setPowerFrequencyCycleCount1(0);
        setDischargecount1(Dischargecount);
        setDischargePhase1(DischargePhase);
        setDischargeTypeProbability1(PDTypeData);
        setDischargeSignalPeak1(DischargeAmount);
        setDischargeSignalAverage1(Average);
        setSpectrumData1(PRPDData);

        setSpectrumGenerationTime(Long.parseLong(formattime));
        if((deviceaddr % 9) == 0)
        setSpectrumProperty((byte)0x02);
        setDeviceName(bdeviceName);
        setDeviceCode(bdeviceCode);
        setMeasurementPointName(bmeasurementPointName);
        setMeasurementPointCode(bmeasurementPointCode);
        setDataType((byte) 1);
        setAmplitudeUnit(Unit);
        setAmplitudeLowerLimit(MinLimit);
        setAmplitudeUpperLimit(MaxLimit);
        setBandwidth(BandWidth);
        setPhaseWindowCount(phaseWindowCount);
        setAmplitudeQuantization(0);
        setPowerFrequencyCycleCount(powerFrequencyCycleCount);
        setDischargecount(Dischargecount);
        setDischargePhase(DischargePhase);
        setDischargeTypeProbability(PDTypeData);
        setDischargeSignalPeak(DischargeAmount);
        setDischargeSignalAverage(Average);
        setSpectrumData(PRPSData);

        return this;
    }

    public DataFileHeader setDefaultDataFile(Appdevice ad, int deviceaddr) {
        String currentPath = System.getProperty("user.dir");
        return setDataFile(ad, deviceaddr, readFileToMqttMessage(currentPath + "\\pds1.txt"));
    }

    public DataFileHeader() {
        // TODO Auto-generated constructor stub
    }

    public MqttMessage readFileToMqttMessage(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            ClassPathResource resource = new ClassPathResource(filePath);
            File file = new File(filePath);
            byte[] fileData = new byte[(int) file.length()];
            FileInputStream fis = new FileInputStream(file);
            fis.read(fileData);
            fis.close();
            String content = new String(fileData, StandardCharsets.UTF_8);
            MqttMessage mqttMessage = new MqttMessage(content.getBytes(StandardCharsets.UTF_8));
            return mqttMessage;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
